﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SyndicateDAO.DatabaseObject;
using System.Web.UI.HtmlControls;
using SyndicateBusiness.Classes;

namespace BigLotterySyndicate.Secured.Draws.Controls
{
    public partial class TabPlayers : Base
    {
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Visible)
                return;

            this.PlaceHolderAddPlayer.Visible = !this.DrawLocked;



            PlaceHolderAddFreePlayer.Visible = true;

            this.ButtonRemovePlayer.Visible = !this.DrawLocked;

            int linesCount = this.Lines.Count();

            //int players = this.PaidPlayers.Count();

            this.ButtonRemovePlayer.Visible = true;

            PlaceHolderGlobalCheckBox.Visible = this.ButtonRemovePlayer.Visible;

            SetList();
        }

        private void SetList()
        {
            if (Page.IsPostBack)
                return;

            BindList();
        }

        private void BindList()
        {
            var query = this.BasePage.BusinessFacade.PlayerBL.GetAllByDrawId(CurrentDraw.id).OrderBy(p=>p.user.username);

            if (query.Count() > 0)
            {
                this.RepeaterList.DataSource = query;
                this.RepeaterList.ItemDataBound += new RepeaterItemEventHandler(RepeaterList_ItemDataBound);
                this.RepeaterList.DataBind();

                this.MultiViewList.SetActiveView(this.ViewList);
            }
            else
            {
                this.MultiViewList.SetActiveView(this.ViewEmpty);
            }
        }

        void RepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            player p = e.Item.DataItem as player;

            ((System.Web.UI.HtmlControls.HtmlInputCheckBox)e.Item.FindControl("chkAction")).Value = String.Format("playerId_{0}", p.id);

            ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = this.DrawOpen;
            /*
            if (!p.freePlay)
            {
                int linesCount = this.Lines.Count();

                int players = this.PaidPlayers.Count();

                ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = linesCount < players;
            }
            else
             * */
            ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = true;
            // if (this.Lines.Count() > e.Item.ItemIndex + 1)
            //    ((PlaceHolder)e.Item.FindControl("PlaceHolderAction")).Visible = false;



        }

        protected string PrintPlayerName(Object data)
        {
            player p = data as player;

            return p.user.username + (p.freePlay ? "*" : "");

        }

        public string PrintPlayersEmails()
        {
            return String.Join(";",Players.Select(p => p.user.email).ToArray());
        }

        protected void ButtonRemovePlayer_Click(object sender, EventArgs e)
        {
            bool actionPeformed = false;



            ControlCollection repeaterRows = this.FindControl("RepeaterList").Controls;
            HtmlInputCheckBox cb;

            int linesCount = this.Lines.Count();

            int players = this.Players.Count();

            foreach (Control row in repeaterRows)
            {
                cb = (System.Web.UI.HtmlControls.HtmlInputCheckBox)row.FindControl("chkAction");
                if (cb.Checked)
                {
                    int? ObjectId = Utilities.StringToInt(cb.Value.Replace("playerId_", ""));

                    if (ObjectId.HasValue)
                    {
                        player p = this.BasePage.BusinessFacade.PlayerBL.GetAllByDrawId(CurrentDraw.id).SingleOrDefault(pl => pl.id == ObjectId.Value);

                        if (p != null)
                        {
                            int userId = p.userId;
                            int pid = p.id;
                            bool freePlayer = p.freePlay;

                            if (this.BasePage.BusinessFacade.PlayerBL.DeletePlayer(p))
                            {
                                InsertEventLogEntry("Player [" + pid.ToString() + "] removed.");

                                user u = this.BasePage.BusinessFacade.UserBL.GetSingleUser(userId);
                                if (!freePlayer)
                                {
                                    if (this.CurrentDraw.type == draw.drawType.LOTTO)
                                        u.funds++;
                                    else
                                        u.funds = u.funds + 2;




                                    if (this.BasePage.BusinessFacade.UserBL.UpdateUser())
                                    {
                                        fundsLog logEntry = new fundsLog();

                                        logEntry.moneyIn = true;

                                        logEntry.fromUserId = this.BasePage.LoggedInUser.id;
                                        logEntry.toUserId = userId;
                                        logEntry.dateCreated = DateTime.Now;
                                        if (this.CurrentDraw.type == draw.drawType.LOTTO)
                                            logEntry.amount = 1;
                                        else
                                            logEntry.amount = 2;

                                        logEntry.syndicateId = this.BasePage.LoggedInUser.syndicateId;
                                        logEntry.description = String.Format("Refund. Player removed from draw {0}", PrintDrawDate());

                                        this.BasePage.BusinessFacade.FundsLogBL.InsertEntry(logEntry);

                                        InsertEventLogEntry("User [" + userId.ToString() + "] funds updated.");

                                        players--;

                                    }
                                }
                                else
                                {
                                    fundsLog logEntry = new fundsLog();

                                    logEntry.moneyIn = true;

                                    logEntry.fromUserId = this.BasePage.LoggedInUser.id;
                                    logEntry.toUserId = userId;
                                    logEntry.dateCreated = DateTime.Now;
                                    
                                        logEntry.amount = 0;

                                    logEntry.syndicateId = this.BasePage.LoggedInUser.syndicateId;
                                    logEntry.description = String.Format("Free player removed from draw {0}", PrintDrawDate());

                                    this.BasePage.BusinessFacade.FundsLogBL.InsertEntry(logEntry);

                                    //InsertEventLogEntry("User [" + userId.ToString() + "] funds updated.");

                                    players--;
                                }

                                if (!actionPeformed)
                                    actionPeformed = true;
                            }
                        }
                    }
                }

            }

            if (actionPeformed)
            {

                this.BindList();
            }
        }        
    }
}